#! /usr/bin/python

import sys
import strips_engine
from search import *
import utils

def execute():
	if len(sys.argv) != 7:
		raise SystemExit("Please input all arguments\n\nsearch_engine.py -domain <domain.pddl> -problem <problem.pddl> -search [bfs|dfs|ids|ucs|bfgs|astar]")

	domain_file = sys.argv[2]
	problem_file = sys.argv[4]
	search_algorithm = sys.argv[6]

	problem = strips_engine.loadIntoProblem(domain_file, problem_file)
	node = plan_search(search_algorithm, problem)
	print_save_path(search_algorithm, node)

def plan_search(search_algorithm,problem):
	if search_algorithm == "bfs":
		return breadth_first_graph_search(problem)
	elif search_algorithm == "dfs":
		return depth_first_graph_search(problem)
	elif search_algorithm == "ids":
		return iterative_deepening_search(problem)
	elif search_algorithm == "ucs":
		return uniform_cost_search(problem)
	elif search_algorithm == "bfgs":
		return best_first_graph_search(problem, problem.h)
	elif search_algorithm == "astar":
		return astar_search(problem)
	else:
		raise SystemExit("Please use only one of the following algorithms (bfs|dfs|ids|ucs|bfgs|astar)")



def print_save_path(search_algorithm, n):
	if n is not None:
		try:
			print "Plan found!"
			print "writing to solution using %s algorithm to solution.txt..."%search_algorithm
			f = open("solutions.txt", 'w')
			f.write("; sol using %s \n" %search_algorithm)
			l = n.path()
			for p in l:
				f.write("%s"%p)
			f.close()
			print "done..."
		except Exception , msg:
			print "Error: ", msg
	else:
		print "No Plan Found!!"


	print 

if __name__ == "__main__":
	sys.path.append("AIMA/")
	execute()

